<template>
  <div>
    <!-- app-title是子组件 面包屑 -->
    <app-title :mainTitle="mainTitle"></app-title>

    <!-- 查询表单 -->
    <el-form :inline="true" :model="search" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input
          v-model="search.name"
          placeholder="姓名"
          style="width:130px"
        ></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="search.sex" placeholder="性别" style="width:100px">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="onSubmit"
          >查询</el-button
        >
        <el-button type="success" icon="el-icon-plus" @click="popupDialog"
          >添加</el-button
        >
        <el-button type="warning" icon="el-icon-refresh" @click="resetSearch"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 用户列表 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column type="index" label="序号" width="50"> </el-table-column>
      <el-table-column prop="name" label="姓名" width="80"> </el-table-column>
      <el-table-column prop="sex" label="性别" width="50"> </el-table-column>
      <el-table-column prop="birthday" label="出生日期"> </el-table-column>
      <el-table-column prop="address" label="地址"> </el-table-column>
      <el-table-column prop="phone" label="手机号码"> </el-table-column>
      <el-table-column label="头像" width="72">
        <template slot-scope="scope">
          <img :src="scope.row.pic" alt=" " style="width:50px" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row._id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页效果 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[15, 30, 45, 60]"
      :page-size="25"
      layout="->, total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 弹框(模态框)-->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogFormVisible"
      center
      width="45%"
    >
      <el-form
        ref="addForm"
        :rules="rules"
        :model="addForm"
        label-width="150px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="addForm.name"
            placeholder="请输入姓名"
            autocomplete="off"
            style="width:190px"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="addForm.sex">
            <el-radio label="男" value="male"></el-radio>
            <el-radio label="女" value="female"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker
            v-model="addForm.birthday"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            style="width:190px"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="addForm.phone"
            placeholder="请输入手机号"
            autocomplete="off"
            style="width:190px"
          ></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input
            type="textarea"
            v-model="addForm.address"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="头像">
          <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            :limit="3"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <!-- <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div> -->
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser('addForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import usersApi from "@/api/userApi.js";
import appTitle from "@/components/mainTitle";
export default {
  name: "Index",
  data() {
    let phoneRule = (rule, value, callback) => {
      let val = /^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(value);
      if (!value) {
        callback(new Error("手机号码不能为空"));
      } else if (!val) {
        callback(new Error("请正确书写手机号码格式"));
      } else {
        callback();
      }
    };
    return {
      mainTitle: "评论管理", // 面包屑
      tableData: [], // 页面数据
      // 渲染数据分页效果
      page: 1,
      pagesize: 15,
      // 查询表单
      search: {
        name: "",
        sex: ""
      },
      total: 0,
      currentPage: 1, //默认显示的页数
      dialogFormVisible: false, // 弹框

      addForm: {
        name: "",
        sex: "",
        birthday: "",
        phone: "",
        address: ""
        // pic: ""
      },
      // 表单验证
      rules: {
        name: [{ required: true, message: "姓名不能为空", trigger: "change" }],
        phone: [{ validator: phoneRule, trigger: "blur" }]
      },
      // 上传文件
      fileList: [
        // {
        //   name: "food.jpeg",
        //   url:
        //     "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"
        // },
        // {
        //   name: "food2.jpeg",
        //   url:
        //     "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"
        // }
      ]
    };
  },

  methods: {
    // 获取数据渲染
    renderData() {
      let search = {};
      if (this.search.name && !this.search.sex) {
        // console.log("仅名字");
        search = { name: this.search.name };
      } else if (!this.search.name && this.search.sex) {
        // console.log("仅性别");
        search = { sex: this.search.sex };
      } else if (this.search.name && this.search.sex) {
        // console.log("全选");
        search = { name: this.search.name, sex: this.search.sex };
      }
      // 发送请求
      usersApi
        .getusers(this.page, this.pagesize, search)
        .then(res => {
          this.total = res.data.total; //设置总条数
          this.tableData = res.data.data; //数据部分
        })
        .catch(err => {
          console.log("出错了" + err);
        });
    },

    // 查询按钮功能
    onSubmit() {
      this.renderData();
    },

    //重置按钮功能
    resetSearch() {
      // 查找规则不为空的时候，才去发请求；
      if (this.search.name || this.search.sex) {
        this.search.name = "";
        this.search.sex = "";
        this.renderData();
      }
    },

    // 添加用户按钮，点击弹出编辑窗口
    popupDialog() {
      this.dialogFormVisible = true;
    },

    // 确认添加用户
    addUser(formName) {
      // console.log("没有通过验证");
      this.$refs[formName].validate(valid => {
        if (valid) {
          // console.log("通过了验证");
        }
      });

      // dialogFormVisible = false;
    },

    // 编辑操作
    handleEdit(index, row) {
      // 表格index是下标，row是数据对象
      // console.log(index, row);
    },

    // 删除操作
    handleDelete(id) {
      this.$confirm("是否确定删除该用户信息?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 发送请求
          usersApi
            .deluser(id)
            .then(res => {
              // 删除成功
              if (res.data.code) {
                // 提示用户
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                this.renderData();
              }
            })
            .catch(err => {
              console.log("出错了" + err);
            });
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        });
    },

    // 分页的方法
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pagesize = val;
      this.renderData();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page = val;
      this.renderData();
    },

    // 文件上传
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    handlePreview(file) {
      // console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    }
  },

  components: {
    appTitle
  },

  created() {
    // 页面刷新渲染数据；
    this.renderData();
  }
};
</script>

<style scoped lang='scss'>
// 表单样式
.el-form {
  padding-left: 10px;
  .el-form-item {
    margin: 20px 10px;
  }
}
// 数据列表
.el-table {
  margin-bottom: 35px;
}
// 分页样式
.el-pagination {
  position: fixed;
  width: 100%;
  right: 0;
  bottom: 0;
  // overflow-y: auto;
  background-color: white;
}
</style>